/**
 * @(#)PDUtils.java 1.0 2013/9/4
 * Copyright 2013 PD, Inc. All rights reserved.
 */
package cn.broadin.app.hotel.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import cn.broadin.app.hotel.factory.ApplicationFactory;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * PDUtils pd工具类
 * @author fenghui
 *
 */
public class PDUtils {
	private static final String TAG = "PDUtils";				//log tag
	private String macAddress_str = "", macAddress_num = "";		//mac地址
	private SharedPreferencesUtil sharedPreferencesUtil = null;		//存储数据
	private static PDUtils pdUtilInstance = null;			//pd对象实例
	
	
	private PDUtils() {}
	
	/**
	 * 获取工具类对象
	 * @return
	 */
	public static PDUtils getInstance() {
		if(pdUtilInstance == null) {
			pdUtilInstance = new PDUtils();
		}
		return pdUtilInstance;
	}
	
	/**
	 * 获取mac地址
	 * @param ctx
	 * @param getStringMac	获取string格式还是int格式，true为String，false为int格式
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public String getMacAddress(Context ctx, boolean getStringMac) {
		if(!ApplicationFactory.getApplication().IS_NEED_GETSTBMAC()) return "123456";
		if(macAddress_str.equals("")) {
			//从存储文件中获取mac信息
			sharedPreferencesUtil = new SharedPreferencesUtil(ctx);
			//macAddress_str = sharedPreferencesUtil.getValue("pd_mac_str");
			//macAddress_num = sharedPreferencesUtil.getValue("pd_mac_num");
			//没有从存储位置获取到mac地址
			String[] macAddArr = null;
			if(macAddress_str.equals("") && ApplicationFactory.getApplication().GET_WIFIMAC_FIRST()) {
				Log.d("caolm:","get wifi mac");
				WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
				//鉴权获取的是wifi还是有线mac
				if(wifiMgr.isWifiEnabled()) {
					WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
					if (null != info) {
						macAddress_str = info.getMacAddress();
					}
				}
			}
			if(macAddress_str.equals("")) {
				macAddress_str = getLineMacAddress("eth");
			}
			Log.i(TAG, "mac addr str : " + macAddress_str);
			macAddress_str = macAddress_str.replaceAll("\\.", ":");
			macAddress_str = macAddress_str.replaceAll("-", ":");
			macAddress_str = macAddress_str.toLowerCase();
			
			if(macAddress_str.indexOf(":") > -1) {
				macAddArr = macAddress_str.split(":");
			} else {
				macAddArr = new String[0];
			}
			String tempResult = "";
			for(int i = 0; i < macAddArr.length; i++) {
				tempResult += Integer.parseInt(macAddArr[i], 16) + "";
			}
			macAddress_num = Long.parseLong(tempResult) + "";
			//持久化保存
			java.util.Map<String, String> values = new java.util.HashMap<String, String>();
			values.put("pd_mac_str", macAddress_str);
			values.put("pd_mac_num", macAddress_num);
			sharedPreferencesUtil.setValues(values);
			sharedPreferencesUtil = null;
		}
		String returnMac = getStringMac ? macAddress_str : macAddress_num;
		Log.i(TAG, "getMac result: " + returnMac);
		return returnMac;
	}
	
	/**
	 * 获取有线网络mac地址
	 * @param name
	 * @return
	 */
	@SuppressLint({ "NewApi", "DefaultLocale"})
	private String getLineMacAddress(String name) {
		Log.d("caolm:","get net mac");
		try {
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface intf = en.nextElement();
				if (intf.getName().toLowerCase().contains(name)) {
					byte[] ha = intf.getHardwareAddress();
					if (ha != null) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < ha.length; ++i) {
							if (i > 0) {
								sb.append(":");
							}
							sb.append(String.format("%1$02x", ha[i]));
						}
						return sb.toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e(TAG, "getLineMacAddress error. " + ex.getMessage());
		}
		return "";
	}
	
	/**
	 * 获取http数据请求
	 * @param serverPath 请求地址
	 * @return
	 */
	@SuppressWarnings("finally")
	public String getHttpRequest(String serverPath) {
		StringBuilder jsonStr = new StringBuilder();
		try {
			HttpClient client = new DefaultHttpClient();							// 新建http客户端
			HttpParams httpParams = client.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 3000);			// 设置连接超时范围
			HttpConnectionParams.setSoTimeout(httpParams, 5000);
			HttpResponse response = client.execute(new HttpGet(serverPath));
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						entity.getContent(), "UTF-8"), 8192);
				String line = null;
				while ((line = reader.readLine()) != null) {
					jsonStr.append(line + "\n");									// 按行读取放入StringBuilder中
				}
				reader.close();
			}
		} catch (Exception e) {
			Log.e("PDUtils.getJSONStr", e.getMessage());
		} finally {
			return jsonStr.toString();
		}
	}
	
	/**
	 * 获取指定包名的应用程序的版本号
	 * @param context		context
	 * @param packageName	包名称
	 * @return				版本号
	 */
	public int getVerCode(Context context, String packageName){
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
		} catch (Exception e) {
			Log.e(TAG, "getVerCode error. message is :" + e.getMessage());
		}
		return verCode;
	}
	
	/**
	 * 下载程序
	 * @param downPath
	 * @param fileName
	 */
	public void downAppFile(String downPath, String fileName, Handler handler, Activity ctx) {
		Log.i(TAG, "downAppFile path : " + downPath);
		Message msg = null;
		try {
			URL url = new URL(downPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			long length = conn.getContentLength();
			msg = handler.obtainMessage();
			msg.what = -1;
			msg.obj = length;
			handler.sendMessage(msg);
			Log.i(TAG, "downAppFile size is : " + length);
			InputStream is = conn.getInputStream();
			FileOutputStream fileOutputStream = null;
			if (is == null) {
				//发送下载出错状态
				msg = handler.obtainMessage();
				msg.what = 2;
				handler.sendMessage(msg);
				Log.e(TAG, "downAppFile error. InputStream is null!");
				return;
			}
			File file = new File(Environment.getExternalStorageDirectory(), fileName);
			fileOutputStream = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buf = new byte[1024];
			int ch = -1;
			int total = 0;
			do {
				ch = bis.read(buf);
				if (ch <= 0)
					break;
				fileOutputStream.write(buf, 0, ch);
				total += ch;
				//发送进度状态
				msg = handler.obtainMessage();
				msg.what = 0;
				msg.arg1 = total;
				handler.sendMessage(msg);
			} while (true);
			//发送下载完毕状态
			msg = handler.obtainMessage();
			msg.what = 1;
			handler.sendMessage(msg);
			
			conn.disconnect();
			fileOutputStream.close();
			bis.close();
			is.close();
			//安装apk
			installApk(file, ctx);
		} catch (MalformedURLException e) {
			//发送下载出错状态
			msg = handler.obtainMessage();
			msg.what = 2;
			handler.sendMessage(msg);
			Log.e(TAG, "downAppFile error." + e.getMessage());
		} catch (FileNotFoundException e) {
			//发送下载出错状态
			msg = handler.obtainMessage();
			msg.what = 2;
			handler.sendMessage(msg);
			Log.e(TAG, "downAppFile error." + e.getMessage());
		} catch (IOException e) {
			//发送下载出错状态
			msg = handler.obtainMessage();
			msg.what = 2;
			handler.sendMessage(msg);
			Log.e(TAG, "downAppFile error. " + e.getMessage());
		}
	}
	
	/**
	 * 安装apk
	 * @param file	文件
	 * @param ctx	context
	 */
	public void installApk(File file, Activity ctx) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);				//执行动作
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");	//执行的数据类型
		ctx.startActivity(intent);
		ctx.finish();
	}
}